package org.jinyan.utils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.jinyan.constant.RemoteServiceConstant;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class RemoteServiceUtil {

	private Logger logger = Logger.getLogger(RemoteServiceUtil.class);

	private HttpGet createHttpMethod(String url) throws HttpException,
			IOException {
		String time = String.valueOf(System.currentTimeMillis());
		Md5 md5 = new Md5();
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet method = new HttpGet("http://www.baidu.com");// HTTP
																// Get请求(POST雷同)
		RequestConfig requestConfig = RequestConfig.custom()
				.setSocketTimeout(2000).setConnectTimeout(2000).build();// 设置请求和传输超时时间
		method.setConfig(requestConfig);
		httpClient.execute(method);// 执行请求
		return method;
	}

	public static Map<String, Object> doHttpGetMethod(String url, Map params)
			throws HttpException, IOException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String time = String.valueOf(System.currentTimeMillis());
		Md5 md5 = new Md5();
		HttpClient httpClient = new DefaultHttpClient();
		List<NameValuePair> nvps = mapToNameValuePair(params);
		URI uri = null;
		try {
			if (nvps.isEmpty()) {
				uri = new URIBuilder().setPath(url).build();
			} else {
				uri = new URIBuilder().setPath(url).setParameters(nvps).build();
			}

		} catch (URISyntaxException e) {
			e.printStackTrace();
			return resultMap = doErrorMap(-1, "构建URI执行异常");
		}

		HttpGet method = new HttpGet(uri);// HTTP
		RequestConfig requestConfig = RequestConfig.custom()
				.setSocketTimeout(RemoteServiceConstant.SOCKETTIMEOUT * 2)
				.setConnectTimeout(RemoteServiceConstant.CONNECTTIMEOUT * 2)
				.build();// 设置请求和传输超时时间
		method.setConfig(requestConfig);

		HttpResponse response = httpClient.execute(method);
		int statusCode = response.getStatusLine().getStatusCode();
		HttpEntity entity = response.getEntity();
		String respStr = "";
		if (entity != null) {
			respStr = EntityUtils.toString(entity, "UTF-8");
		}
		Type type = new TypeToken<Map<String, Object>>() {
		}.getType();
		if (statusCode == 200) {
			resultMap = new Gson().fromJson(respStr, type);
		} else {
			resultMap = doErrorMap(statusCode, respStr);
		}

		return resultMap;
	}

	private static List<NameValuePair> mapToNameValuePair(
			Map<String, Object> params) {
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		if (params == null) {
			return formparams;
		}
		for (Entry<String, Object> entry : params.entrySet()) {
			String name = (String) entry.getKey();
			String value = (String) entry.getValue();
			NameValuePair temp = new BasicNameValuePair(name, value);
			formparams.add(temp);
		}
		return formparams;
	}

	private static Map doErrorMap(int statusCode, String respStr) {
		Map errorMap = new HashMap<String, Object>();
		errorMap.put("statusCode", statusCode);
		errorMap.put("response", respStr);
		errorMap.put("error", "fllll");
		return errorMap;
	}

	private Map createHttpMethod(Map<String, Object> param, String url)
			throws HttpException, IOException {
		String time = String.valueOf(System.currentTimeMillis());
		Md5 md5 = new Md5();
		CloseableHttpClient httpClient = HttpClients.createDefault();
		Map resultMap = new HashMap<String, Object>();
		Gson gson = new Gson();
		HttpPost postMethod = new HttpPost(url);
		postMethod.addHeader("Content-Type",
				"application/x-www-form-urlencoded; charset=UTF-8");
		RequestConfig requestConfig = RequestConfig.custom()
				.setSocketTimeout(RemoteServiceConstant.SOCKETTIMEOUT)
				.setConnectTimeout(RemoteServiceConstant.CONNECTTIMEOUT)
				.build();// 设置请求和传输超时时间

		postMethod.setConfig(requestConfig);
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		// formparams.add(new BasicNameValuePair("userCode", userCode));
		// formparams.add(new BasicNameValuePair("password", password));
		// formparams.add(new BasicNameValuePair("clientVersion",
		// clientVersion));
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			postMethod.setEntity(uefEntity);
			HttpResponse response = httpClient.execute(postMethod);
			int statusCode = response.getStatusLine().getStatusCode();
			HttpEntity entity = response.getEntity();
			String respStr = "";
			if (entity != null) {
				respStr = EntityUtils.toString(entity, "UTF-8");
			}
			if (statusCode == 200) {

			} else if (statusCode == 500) {

			} else {
				resultMap.put("result", "error");

				resultMap.put("errorMess", respStr);
				resultMap.put("errorCode", statusCode);
				logger.info(new StringBuffer("用户登录服务器端验证失败，返回的状态码：")
						.append(statusCode).append("错误信息返回").append(respStr));
			}
		} catch (Exception e) {
			resultMap.put("result", "error");
			resultMap.put("errorMess",
					"客户端用户登陆时与服务连接失败。" + e.getLocalizedMessage());
			resultMap.put("errorCode", "-1");
			e.printStackTrace();
			logger.info("[客户端用户登陆时  执行异常，异常如下:]");
			Logger.getLogger(getClass()).info(e.getLocalizedMessage(), e);
			logger.error("[客户端用户登陆时  执行异常，原因如下:]");
			Logger.getLogger(getClass()).error(e.getLocalizedMessage(), e);
			return resultMap;
		} finally {
			if (postMethod != null) {
				postMethod.abort();
				postMethod.releaseConnection();
				logger.info("[客户端用户登陆链接释放成功]");
			}
		}

		return resultMap;
	}

}
